import 'package:bloc/bloc.dart';
import 'package:qgchat/common/action/filter/index.dart';
import 'event.dart';
import 'repository.dart';
import 'state.dart';

///
/// 视频中对话bloc
/// 
class DialogueBloc extends Bloc<DialogueEvent, DialogueState> {
  final VideoTextRepository textRepository;

  DialogueBloc(this.textRepository);

  @override
  DialogueState get initialState => DialogueLoaded();

  @override
  Stream<DialogueState> mapEventToState(DialogueEvent event) async* {
    // 查看对话内容
    if (event is LoadDialogue) {
      yield* _mapLoadTextToState(event);
    }
    // 新增对话内容
    else if (event is AddDialogue) {
      yield* _mapAddTextToState(event);
    }
  }

  Stream<DialogueState> _mapLoadTextToState(LoadDialogue event) async* {
    if (state is DialogueLoading) {
      yield DialogueLoaded(textRepository.texts);
    }
  }

  Stream<DialogueState> _mapAddTextToState(AddDialogue event) async* {
    if (state is DialogueLoaded) {
      String msg = Filter.txt(event.text.msg);
      event.text.msg = msg;
      textRepository.addText(event.text);
      yield DialogueLoaded(textRepository.texts);
    }
  }
}